package com.xnf.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xnf.model.common.dtos.ResponseResult;
import com.xnf.model.common.enums.AppHttpCodeEnum;
import com.xnf.model.user.dtos.LoginDto;
import com.xnf.model.user.pojos.ApUser;
import com.xnf.user.mapper.ApUserMapper;
import com.xnf.user.service.ApUserLoginService;
import com.xnf.utils.common.AppJwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by xnf on 2022/3/8.
 */
@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.校验参数
        if(dto.getEquipmentId() == null && (StringUtils.isEmpty(dto.getPassword())&&StringUtils.isEmpty(dto.getPassword()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //手机号码密码登录
        if (!StringUtils.isEmpty(dto.getPhone()) && !StringUtils.isEmpty(dto.getPassword())){
            //ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser != null){
                String pswd = DigestUtils.md5Hex((dto.getPassword() + apUser.getSalt()).getBytes());
                System.out.println(apUser.getSalt());
                System.out.println(DigestUtils.md5Hex(("admin"+apUser.getSalt()).getBytes()));
                System.out.println(pswd);
                if (pswd.equals(apUser.getPassword())){
                    Map<String,Object> map = new HashMap<>();
                    apUser.setPassword("");
                    apUser.setSalt("");
                    map.put("user",apUser);
                    map.put("userId ",apUser.getId());
                    map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                    return ResponseResult.okResult(map);
                }else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
        }else{
            //设备登录
            if (dto.getEquipmentId() == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }
    }
}
